package com.css.zfzx.sjcj.modules.hddcDrillProfile.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.css.zfzx.sjcj.common.utils.EasyPoiExcelUtil;
import com.css.zfzx.sjcj.common.utils.UpdateUtil;
import com.css.zfzx.sjcj.modules.hddcB3DrillProjectTable.repository.entity.HddcB3DrillprojecttableEntity;
import com.css.zfzx.sjcj.modules.hddcB3DrillProjectTable.service.HddcB3DrillprojecttableService;
import com.css.zfzx.sjcj.modules.hddcDrillProfile.repository.HddcDrillprofileNativeRepository;
import com.css.zfzx.sjcj.modules.hddcDrillProfile.repository.HddcDrillprofileRepository;
import com.css.zfzx.sjcj.modules.hddcDrillProfile.repository.entity.HddcDrillprofileEntity;
import com.css.zfzx.sjcj.modules.hddcDrillProfile.service.HddcDrillprofileService;
import com.css.zfzx.sjcj.modules.hddcDrillProfile.viewobjects.HddcDrillprofileQueryParams;
import com.css.zfzx.sjcj.modules.hddcDrillProfile.viewobjects.HddcDrillprofileVO;
import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.sys.dict.repository.entity.DictItemEntity;
import com.css.bpm.platform.utils.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @author zyb
 * @date 2020-11-30
 */
@Service
public class HddcDrillprofileServiceImpl implements HddcDrillprofileService {

    @Autowired
    private HddcDrillprofileRepository hddcDrillprofileRepository;
    @Autowired
    private HddcDrillprofileNativeRepository hddcDrillprofileNativeRepository;
    @Autowired
    private HddcB3DrillprojecttableService hddcB3DrillprojecttableService;

    @Override
    public JSONObject queryHddcDrillprofiles(HddcDrillprofileQueryParams queryParams, int curPage, int pageSize,String sort,String order) {
        Page<HddcDrillprofileEntity> hddcDrillprofilePage = this.hddcDrillprofileNativeRepository.queryHddcDrillprofiles(queryParams, curPage, pageSize, sort, order);
        JSONObject jsonObject = PlatformPageUtils.formatPageData(hddcDrillprofilePage);
        return jsonObject;
    }


    @Override
    public HddcDrillprofileEntity getHddcDrillprofile(String id) {
        HddcDrillprofileEntity hddcDrillprofile = this.hddcDrillprofileRepository.findById(id).orElse(null);
        return hddcDrillprofile;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcDrillprofileEntity saveHddcDrillprofile(HddcDrillprofileEntity hddcDrillprofile) {
        String uuid = UUIDGenerator.getUUID();
        hddcDrillprofile.setUuid(uuid);
        hddcDrillprofile.setCreateUser(PlatformSessionUtils.getUserId());
        hddcDrillprofile.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
        hddcDrillprofile.setIsValid("1");
        this.hddcDrillprofileRepository.save(hddcDrillprofile);
        return hddcDrillprofile;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcDrillprofileEntity updateHddcDrillprofile(HddcDrillprofileEntity hddcDrillprofile) {
        UpdateUtil.copyNullProperties(hddcDrillprofileRepository.findByUuidAndIsValid(hddcDrillprofile.getUuid(),
                "1"), hddcDrillprofile);
        hddcDrillprofile.setUpdateUser(PlatformSessionUtils.getUserId());
        hddcDrillprofile.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        this.hddcDrillprofileRepository.save(hddcDrillprofile);
        return hddcDrillprofile;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteHddcDrillprofiles(List<String> ids) {
        List<HddcDrillprofileEntity> hddcDrillprofileList = this.hddcDrillprofileRepository.findAllById(ids);
        if (!PlatformObjectUtils.isEmpty(hddcDrillprofileList) && hddcDrillprofileList.size() > 0) {
            for (HddcDrillprofileEntity hddcDrillprofile : hddcDrillprofileList) {
                hddcDrillprofile.setIsValid("0");
                hddcDrillprofile.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcDrillprofile.setUpdateTime(new Date());
                this.hddcDrillprofileRepository.save(hddcDrillprofile);
            }
        }
    }

    @Override
    public HddcDrillprofileEntity findById(String id) {
        HddcDrillprofileEntity hddcDrillprofileEntity = hddcDrillprofileRepository.findbyId(id);
        return hddcDrillprofileEntity;
    }

    @Transactional
    @Override
    public int dataQualityCheck() {
        List<HddcDrillprofileEntity> listAll = hddcDrillprofileRepository.findByAll();
        ArrayList<String> list = new ArrayList<>();
        for (HddcDrillprofileEntity b2All : listAll) {
            if (!list.contains(b2All.getProjectid())&& !StringUtils.isEmpty(b2All.getProjectid())) {
                list.add(b2All.getProjectid());
            }
        }
        if (null == list || list.size() == 0) {
            return 1;
        }
        for (String id : list) {
            String str = "";
            HddcB3DrillprojecttableEntity hddcB3DrillprojecttableEntity = hddcB3DrillprojecttableService.findById(id);
            if (hddcB3DrillprojecttableEntity == null) {
                hddcDrillprofileRepository.updateStatus("2", "质检失败", id);
                continue;
            }
            int total1 = 0;
            for (HddcDrillprofileEntity b2All : listAll) {
                if (b2All.getProjectid().equals(id)) {
                    if (b2All.getDrillingholecount() != null && !b2All.getDrillingholecount().equals("")) {
                        total1 += b2All.getDrillingholecount();
                    }
                }
            }
            if (!(total1 == hddcB3DrillprojecttableEntity.getDrillcount())) {
                str += "钻孔数失败.";

            }
            if (str.isEmpty()) {
                str += "质检成功";
                hddcDrillprofileRepository.updateStatus("1", str, id);
            } else {
                hddcDrillprofileRepository.updateStatus("2", str, id);
            }
        }
        return 1;
    }


    @Override
    public List<DictItemEntity> getValidDictItemsByDictCode(String dictCode) {
        List<DictItemEntity> validDictItems = PlatformAPI.getDictAPI().getValidDictItemsByDictCode(dictCode);
        return validDictItems;
    }

    @Override
    public void exportFile(HddcDrillprofileQueryParams queryParams, HttpServletResponse response) {
        List<HddcDrillprofileEntity> yhDisasterEntities = hddcDrillprofileNativeRepository.exportYhDisasters(queryParams);
        List<HddcDrillprofileVO> list=new ArrayList<>();
        for (HddcDrillprofileEntity entity:yhDisasterEntities) {
            HddcDrillprofileVO yhDisasterVO=new HddcDrillprofileVO();
            BeanUtils.copyProperties(entity,yhDisasterVO);
            list.add(yhDisasterVO);
        }
        EasyPoiExcelUtil.exportExcel(list, "跨断层钻探剖面-线", "跨断层钻探剖面-线", HddcDrillprofileVO.class, "跨断层钻探剖面-线.xls", response);
    }

    @Override
    public String exportExcel(MultipartFile file, HttpServletResponse response) {
        try {
            // 返回的消息
            StringBuilder returnMsg = new StringBuilder();
            // 导入的参数信息
            ImportParams params = new ImportParams();
            // 设置简析的第一行
            params.setHeadRows(1);
            // 是否需要校验
            params.setNeedVerify(true);
            // 获取到Excel数据
            ExcelImportResult<HddcDrillprofileVO> result = ExcelImportUtil.importExcelMore(file.getInputStream(), HddcDrillprofileVO.class, params);
            List<HddcDrillprofileVO> list = result.getList();
            // Excel条数据
            int firstList = list.size();
            StringBuilder sb = new StringBuilder();
            //保存
            saveDisasterList(list, sb);
            returnMsg.append("成功导入" + (result.getList().size() ));
            returnMsg.append(sb);
            if (result.isVerifyFail()) {
                // 校验返回失败行信息
                Iterator<HddcDrillprofileVO> iterator = result.getFailList().iterator();
                while (iterator.hasNext()) {
                    HddcDrillprofileVO yhDisasterVO = iterator.next();
                    String error = "";
                    returnMsg.append("第" + yhDisasterVO.getRowNum() + "行" + yhDisasterVO.getErrorMsg() + "<br/>");
                    returnMsg.append(error);
                }
            }
            return returnMsg.toString();
        } catch (Exception e) {

            return "导入失败，请检查数据正确性";
        }
    }

    /**
     * 批量存入库表并且返回错误数量
     *
     * @param list
     * @param message
     * @return
     */
    public void saveDisasterList( List<HddcDrillprofileVO> list, StringBuilder message) {
        for (int i = 0; i < list.size(); i++) {
            HddcDrillprofileEntity yhDisasterEntity = new HddcDrillprofileEntity();
            HddcDrillprofileVO yhDisasterVO = list.get(i);
            // 将VO数据映射拷贝到库表中
            BeanUtils.copyProperties(yhDisasterVO, yhDisasterEntity);
            saveHddcDrillprofile(yhDisasterEntity);
        }
    }

}
